package ordinaryArray;

import org.junit.Test;

/*
 *@description 反转字符串中的单词
 *@author hkfan
 *@version 1.0
 *@create 2025/5/27 09:59
 */
public class LeetCode_151 {

    @Test
    public void test(){
        System.out.println(reverseWords("the sky is blue"));
    }

    public String reverseWords(String s) {
        //1. 反转
        String str = reverse(s.trim(),0,s.trim().length());
        //2. 定义
        int maxLength=1,i=0;
        //3. 循环反转
        for (int j = 0; j <= str.length(); j++) {
            if (j==str.length()||str.charAt(j)==' ' ){
                str = reverse(str,i,j);
                int length = 0;
                if (j!=str.length()){
                    while (str.charAt(j)==' '){
                        j++;
                        length++;
                    }
                    maxLength=Math.max(length,maxLength);
                    i=j;
                }
            }
        }
        //4. 替换空格
        for (int j = maxLength; j >=2; j--) {
            String temp = "";
            for (int k = 0; k < j; k++) {
                temp+=" ";
            }
            str = str.replaceAll(temp," ");
        }
        return str;
    }

    private String reverse(String str, int i, int j) {
        String str1 = str.substring(0,i);
        String str2 = str.substring(i,j);
        String str3 = str.substring(j);
        return str1+new StringBuilder(str2).reverse().toString()+str3;
    }


}
